<?php

class YouNet_Model_DbTable_Users extends YouNet_Db_Table
{
	const TABLE_NAME = 'users';
	protected $_name = self::TABLE_NAME;
	protected $_rowClass = 'YouNet_Model_User';
	
    public function findOneByIdSocial($id_social)
	{
		return $this->fetchRow('id_social = ' . $this->_db->quote($id_social));
	}
	
	public static function getExtendedAccessToken($id_social)
	{
		$key = implode('_',array('fb_extended_access_token', $id_social));
		$extended_access_token = YouNet_Util::getObjectMemCache()->load($key);
		if( $extended_access_token === false )
		{
			$instance = new YouNet_Model_DbTable_Users();
			$select = $instance->select()
					->from(self::TABLE_NAME, 'extended_access_token')
					->where('id_social = ?' ,$id_social);
			$extended_access_token = $instance->getAdapter()->fetchOne($select);
			YouNet_Util::getObjectMemCache()->save($extended_access_token, $key);
		}
		return $extended_access_token;
	}
	
	public static function updateExtendedAccessToken($id_social, $extended_access_token)
	{
		$instance = new self();
		$instance->update(
			array(
				'extended_access_token' => $extended_access_token,
				'time_modified' => time()
			), array('id_social = ?' => $id_social)
		);
		//Invalidate cache
		$key = implode('_', array('fb_extended_access_token', $id_social));
		YouNet_Util::getObjectMemCache()->remove($key);
	}
	public static function getLatestExtendedAccessToken()
	{
		return self::getDefaultAdapter()->fetchOne('select extended_access_token from users order by time_modified DESC LIMIT 1');
	}
}
